package com.sim.simserial.ui

import android.util.Log
import androidx.fragment.app.viewModels
import com.drake.brv.utils.grid
import com.drake.brv.utils.setup
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.infinit.selfhelp.common.base.ViewBindingFragment
import com.sim.serialport.library.seria.SerialManager
import com.sim.serialport.library.seria.ext.asciiToHex
import com.sim.serialport.library.seria.ext.formatString
import com.sim.serialport.library.seria.ext.generate12DigitTimestamp
import com.sim.simserial.R
import com.sim.simserial.databinding.FragmentOrderDetailBinding
import com.sim.simserial.databinding.ItemAllPurchaseMethodBinding
import com.sim.simserial.navigation.MainNavigator
import com.sim.simserial.utils.SerialDataBuilder
import com.sim.simserial.viewmodel.SimViewModel
import com.sim.storage.GoodsBean
import com.sim.storage.ResponseMessageBean
import com.sim.storage.enums.ErrorReply
import com.sim.storage.enums.FunctionCode
import com.sim.storage.enums.TransactionType
import dagger.hilt.android.AndroidEntryPoint
import java.util.ArrayList
import javax.inject.Inject

@AndroidEntryPoint
class OrderDetailFragment : ViewBindingFragment<FragmentOrderDetailBinding>(R.layout.fragment_order_detail) {
    private var isHasGetLastApproved: Boolean = true
    private var responseMessageBean: ResponseMessageBean? = null

    @Inject
    lateinit var homeNavigator: MainNavigator

    private var goodsBeans: ArrayList<GoodsBean>? = null

    @Inject
    lateinit var serialManager: SerialManager

    private val simViewModel by viewModels<SimViewModel>()

    var currentSaleCommand = ""

    override fun initData() {
        super.initData()
        goodsBeans = arguments?.getParcelableArrayList<GoodsBean>("goods")
    }

    override fun initView() {
        super.initView()
        goodsBeans?.let {
            mBinding.tvPrice.text = it.map { it.getPriceFloat() }.sum().toString()
        }

        mBinding.rvAllPurchase.grid(4).setup {
            addType<TransactionType>(R.layout.item_all_purchase_method)
            onBind {
                val model = getModel<TransactionType>()
                getBinding<ItemAllPurchaseMethodBinding>().root.setOnClickListener {
                    goodsBeans?.let {
                        val amount = it.map { it.getPriceFloat() }.sum()
                        when (model.codeAsc) {
                            TransactionType.CODE_CREDIT_CARD_SALE_I0.codeAsc -> {
                                // TODO 需要确定 发起sale 后， response 是不是很快先自动回复的， 因为void 需要用到response 中的数据，
//                                showLoadingDialog(requireActivity(), true) {
////                                    val fieldCodeTransactionId = responseMessageBean?.messageData?.find { it.fieldCode == FieldCode.CODE_A1.code.toHex() }?.fieldCode
////                                    val processingGateway = responseMessageBean?.messageData?.find { it.fieldCode == FieldCode.CODE_D7.code.toHex() }?.fieldCode
////
////                                    if (fieldCodeTransactionId != null && processingGateway != null) {
////                                        val buildCreditCardSaleVoid = SerialDataBuilder.buildCreditCardSaleVoid(transactionId = fieldCodeTransactionId, processingGateway = processingGateway)
////                                        simViewModel.sendDataWithACK2(buildCreditCardSaleVoid)
////                                    }
//                                }
                                val digitTimestamp = generate12DigitTimestamp()
                                mBinding.rvLog.addItems("pos - ecn: $digitTimestamp")

                                val buildCreditCardSaleRequest = SerialDataBuilder.buildCreditCardSaleRequest(asciiToHex(digitTimestamp), amount = amount)
                                sendRequest(buildCreditCardSaleRequest)
                            }

                            else -> {
                                val digitTimestamp = generate12DigitTimestamp()
                                mBinding.rvLog.addItems("pos - ecn: $digitTimestamp")
                                val buildAllNetsPurchase = SerialDataBuilder.buildAllNetsPurchaseRequest(asciiToHex(digitTimestamp), amount = amount, transactionType = (getModel() as TransactionType).codeAsc)
                                sendRequest(buildAllNetsPurchase)
                            }
                        }
                    }
                }
            }
        }.models = listOf(TransactionType.CODE_01, TransactionType.CODE_02, TransactionType.CODE_03, TransactionType.CODE_04, TransactionType.CODE_CREDIT_CARD_SALE_I0)
    }

    override fun onEvent() {
        mBinding.tvPay.setOnClickListener {
            goodsBeans?.let {
                val singleEntryPurchase = SerialDataBuilder.buildSingleEntryPurchase(amount = it.map { it.getPriceFloat() }.sum())
                simViewModel.sendDataWithACK2(singleEntryPurchase)
                Log.d("analysisRequestData--", SerialDataBuilder.analysisRequestData(formatString(singleEntryPurchase)).toString())
            }
        }
        mBinding.title.imgBack.setOnClickListener {
            homeNavigator.popBack()
        }
    }

    private fun sendRequest(request: String) {
        currentSaleCommand = request
        isHasGetLastApproved = false
        simViewModel.sendDataWithACK2(request)
    }

    override fun observe() {
        super.observe()
        receiveEvent<SimViewModel.XSimEvent> {
            if (it !is SimViewModel.LogEvent) {
                hideLoadingDialog()
            }
            when (it) {
                is SimViewModel.ResponseEvent -> {
                    responseMessageBean = it.response
                    when (it.response.messageHeader.functionCode) {
                        FunctionCode.CODE_GET_LAST_APPROVED_TRANSACTION_56.code -> {
                            // 获取最后一个approved 的transaction,// TODO 获取 last approved 的 ecn 待确认
//                            if (it.response.messageHeader.ecn == SerialDataBuilder.analysisRequestData(formatString(currentSaleCommand))?.messageHeader?.ecn) {
//                                // 与上一次发送的 比较ECN， 如果是同一个，说明 付款成功了，
//
//                            } else {
//                                //  不一样则说明 上次的付款请求无效
//                                mBinding.tvLog.text = "执行get last approved transaction,并且 ecn 和 最后请求的ecn 不一样，"
//                            }
                        }

                        else -> {
                            val response = it.response
                            sendEvent(SaleSuccess())
                        }
                    }
                    mBinding.rvLog.addItems("response 解析：  ${it.response.toString()}")
                }

                is SimViewModel.LogEvent -> {
                    mBinding.rvLog.addItems("${if (it.isPos) "pos:" else "terminal:"} ${it.log}")
                }

                is SimViewModel.ErrorReplyEvent -> {
                    Log.d("XSimEvent---", it.error.errorTypeName)
                    when (it.error) {
                        ErrorReply.Error_Last_No_Reply -> {
                            if (!isHasGetLastApproved) {
                                isHasGetLastApproved = true
                                // 最后一个是no_reply, 需要获取 last approved transaction, 确认交易是否已通过
                                val buildLastApprovedRequest = SerialDataBuilder.buildLastApprovedRequest()
                                simViewModel.sendDataWithACK2(buildLastApprovedRequest)
                            }
                        }

                        else -> {
                            // TODO 其他弹窗提示操作
                        }
                    }
                }

                is SimViewModel.WrongLRCEvent -> {
                }
            }
        }
    }

    class SaleSuccess()
}